﻿using Infragistics.Win.UltraMessageBox;
using Infragistics.Win.UltraWinMaskedEdit;
using Infragistics.Win.UltraWinTabControl;
using OrBitDataModule.Common;
using OrBitDataModule.Controls;
using OrBitDataModule;
using OrBitDataModule.Contract;
using OrBitDataModule.Interface;
using OrBitDataModule.Models;
using OrBitDataModule.UI.Base;
using OrBitDataModule.UI.Setting;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace OrBitDataModule.Dialog
{
    public partial class AddTask : Form
    {
        private string UniqueId = string.Empty;
        private bool IsEdit;
        private Dictionary<string, SettingForm> settings;

        TaskModel taskModel = null;

        public AddTask(bool isEdit, TaskModel taskModel)
        {
            InitializeComponent();
            this.IsEdit = isEdit;
            this.Icon = isEdit ? Tools.ConvertToIcon(Properties.Resource.编辑) : Tools.ConvertToIcon(Properties.Resource.加);
            this.Text = isEdit ? "修改" : "新增";
            this.cb_protocol.SelectedValueChanged += Cb_protocol_SelectedValueChanged;
            this.Load += AddTask_Load;
            this.taskModel = taskModel;
        }

        private void LoadInfo(TaskModel taskModel)
        {
            this.UniqueId = taskModel.UniqueId;
            this.tb_taskName.Text = taskModel.TaskName;
            this.cb_protocol.Text = taskModel.TaskType;
            this.cb_scriptName.Text = taskModel.ScriptName;
            this.tb_desc.Text = taskModel.TaskDescription;

            SettingForm form = settings[taskModel.TaskType];
            form.LoadSetting(taskModel.ProtocolSetting);
            SetApiSetting(taskModel.ApiName, taskModel.ApiUserName, taskModel.ApiPassword);
        }


        private async void AddTask_Load(object sender, EventArgs e)
        {
            cb_scriptName.DisplayLayout.Bands[0].Columns["DataProtocolScriptId"].Hidden = true;
            cb_scriptName.DisplayLayout.Bands[0].Columns["ScriptName"].Header.Caption = "脚本名称";
            cb_scriptName.DisplayLayout.Bands[0].Columns["ScriptName"].Width = cb_scriptName.Width;

            cb_scriptName.ValueMember = "DataProtocolScriptId";
            cb_scriptName.DisplayMember = "ScriptName";

            cb_apiName.Items.Clear();
            List<string> apiList = await TaskApi.GetAllWebApiList();
            cb_apiName.Items.AddRange(apiList.ToArray());

            cb_scriptName.DataSource = await ScriptApi.GetList();

            //AddApiSetting();
            settings = GetAllSettingForm();
            if (settings?.Count > 0)
            {
                cb_protocol.Items.AddRange(settings.Keys.ToArray());
            }
            if (!IsEdit)
            {
                cb_protocol.SelectedIndex = 0;
            }
            else
            {
                LoadInfo(taskModel);
            }
        }

        /// <summary>
        /// 获取API设置
        /// </summary>
        /// <returns></returns>
        public (string ApiName, string UserName, string Password) GetApiSetting() => (this.cb_apiName.Text, this.tb_UserName.Text, this.tb_password.Text);

        /// <summary>
        /// 设置界面值
        /// </summary>
        /// <param name="apiName"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        public void SetApiSetting(string apiName, string userName, string password)
        {
            this.cb_apiName.Text = apiName;
            this.tb_UserName.Text = userName;
            this.tb_password.Text = password;
        }
        private void Cb_protocol_SelectedValueChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(cb_protocol.Text))
            {
                if (settings.ContainsKey(cb_protocol.Text))
                {
                    panel_Settings.Controls.Clear();
                    SettingForm form = settings[cb_protocol.Text];
                    form.FormBorderStyle = FormBorderStyle.None;
                    form.TopLevel = false;
                    form.Dock = DockStyle.Fill;
                    panel_Settings.Controls.Add(form);
                    form.Show();
                }
            }
        }

        /// <summary>
        /// 获取所有设置界面
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, SettingForm> GetAllSettingForm()
        {
            Dictionary<string, SettingForm> list = new Dictionary<string, SettingForm>();
            List<Type> settingFormTypes = GetSettingFormTypes("OrBitDataModule.UI.Setting");
            foreach (var formType in settingFormTypes)
            {
                SettingForm setting = System.Activator.CreateInstance(formType) as SettingForm;
                list.Add(setting.SettingName, setting);
            }
            return list;
        }

        private List<Type> GetSettingFormTypes(string namespaceName)
        {
            Assembly assembly = Assembly.GetAssembly(typeof(SettingForm));
            var typesInNamespace = assembly.GetTypes().Where(t => t.Namespace == namespaceName);

            var settingFormTypes = typesInNamespace
                .Where(t => t.IsSubclassOf(typeof(Form)) && t.GetInterfaces().Contains(typeof(ISetting)))
                .ToList();

            return settingFormTypes;
        }

        private async void Btn_save_Click(object sender, EventArgs e)
        {
            try
            {
                if (settings.ContainsKey(cb_protocol.Text))
                {
                    SettingForm form = settings[cb_protocol.Text];
                    string taskSetting = form.GetSetting();
                    var (ApiName, UserName, Password) = GetApiSetting();
                    //验证API帐号密码
                    var validateResult = await WebApi.GetAccessTokenAsync(ApiName, UserName, Password);
                    if (!validateResult.Result)
                    {
                        if (UltraMessageBoxManager.Show(this, "配置的接口与账号密码存在错误，确定要继续保存吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes)
                        {
                            return;
                        }
                    }
                    string taskName = this.tb_taskName.Text;
                    string taskDescription = this.tb_desc.Text;
                    string protocol = this.cb_protocol.Text;
                    string dataProtocolScriptId = this.cb_scriptName.Value?.ToString();
                    string webApiName = ApiName;
                    string userName = UserName;
                    string password = Password;

                    var result = await TaskApi.AddTask(this.UniqueId, taskName, protocol, taskDescription, taskSetting, dataProtocolScriptId, webApiName, userName, password);
                    UltraMessageBoxManager.Show(this, result.Message, result.Result ? "提示" : "错误", MessageBoxButtons.OK, result.Result ? MessageBoxIcon.Information : MessageBoxIcon.Error);
                    if (result.Result) this.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void Btn_cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
